package com.example.fqapp.service;

import android.content.Context;
import android.util.Log;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import timber.log.Timber;

public class MQTTManager {
    private static final String TAG = "MQTTManager";
    public static final String SERVER_HOST = "tcp://111.229.63.238:1883";
    private String clientId = "";
    private String userName = "fqMqttBroker";
    private String userPassword = "123456";
    private MqttClient client = null;
    private MqttConnectOptions options;
    private Context mContext;

    private MessageCallBack callBack;
    public MQTTManager(Context context){
        mContext = context;
        clientId +=MqttClient.generateClientId();

        Timber.d("onCreate(), clientId=%s", clientId);
        connect();
    }


    /**
     * 连接服务器
     */
    public void connect(){
        Timber.d("开始连接MQtt");
        // host为主机名，clientId即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
        try {
            client = new MqttClient(SERVER_HOST, clientId, new MemoryPersistence());
        } catch (MqttException e) {
            e.printStackTrace();
            Timber.d("new mqttClient fail, e=%s", e.toString());
            return;
        }
        // MQTT的连接设置
        options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        // 设置连接的用户名
        options.setUserName(userName);
        // 设置连接的密码
        options.setPassword(userPassword.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(30);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(30);
        // 最后的遗言(连接断开时， 发动"close"给订阅了topic该主题的用户告知连接已中断)
        //options.setWill("topic/will", "close".getBytes(), 2, true);
        // 客户端是否自动尝试重新连接到服务器
        //options.setAutomaticReconnect(true);
        // 设置回调
        client.setCallback(mqttCallback);
        try {
            client.connect(options);
        } catch (MqttException e) {
            e.printStackTrace();
            Timber.d("client connect fail, e=%s", e.toString());
            return;
        }
        Timber.d("client connect end, clientId=%s", client.getClientId());

        initSubscribeTopic();
    }

    private void initSubscribeTopic(){
        Timber.d("init subscribe topic");
        subscribeMsg("test/topic", 1);
    }

    /**
     * 订阅消息
     * @param topic 订阅消息的主题
     */
    public void subscribeMsg(String topic,int qos){
        if (client==null) {
            return;
        }
        int[] Qos  = {qos};
        String[] topic1 = {topic};
        try {
            client.subscribe(topic1, Qos);
            Timber.d("开始订阅topic=%s", topic);
        } catch (MqttException e) {
            e.printStackTrace();
            Timber.d("error, topic=%s", topic);
        }
    }

    /**
     * 发布消息
     * @param topic 发布消息主题
     * @param msg 消息体
     * @param isRetained 是否为保留消息
     */
    public void publish(String topic,String msg,boolean isRetained,int qos) {
        Timber.d("enter");
        if (client==null) {

            return;
        }

        MqttMessage message = new MqttMessage();
        message.setQos(qos);
        message.setRetained(isRetained);
        message.setPayload(msg.getBytes());
        try {
            client.publish(topic, message);
        } catch (MqttException e) {
            e.printStackTrace();
            Timber.d("error, publish");
            return;
        }
        Timber.d("topic="+topic+"--msg="+msg+"--isRetained"+isRetained);


    }
    int count=0;

    /**
     * 发布和订阅消息的回调
     *
     */
    MqttCallback mqttCallback = new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            Timber.d("connectionLost: cause=%s", cause.toString());

            if (count > 5) {
                return;
            }
            count++;//5次重连
            Timber.d("断开连接，重新连接"+count+"次"+cause);
            try {
                client.close();
                connect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        //接收消息的回调方法
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            //subscribe后得到的消息会执行到这里面
            Timber.d("mqtt, 接收消息=%s", new String(message.getPayload()));
            if (callBack!=null) {
                callBack.messageSuccess(topic,new String(message.getPayload()));
            }
        }

        //发布消息的回调
        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            //publish后会执行到这里
            Timber.d("发布消息成功的回调, %s", token.isComplete());
        }
    };


    /**
     *  设置接收消息的回调方法
     * @param callBack
     */
    public void setMessageCallBack(MessageCallBack callBack){
        this.callBack = callBack;
    }
    public MessageCallBack getMessageHandlerCallBack(){
        if (callBack!=null) {
            return callBack;
        }
        return null;
    }
    /**
     * 断开链接
     */
    public void disconnect(){
        if (client!=null&&client.isConnected()) {
            try {
                client.disconnect();

            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  判断服务是否连接
     * @return
     */
    public boolean isConnected(){
        if (client!=null) {
            return client.isConnected();
        }
        return false;
    }

    public SSLContext sslContextFromStream(InputStream inputStream) throws Exception {

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Certificate certificate = certificateFactory.generateCertificate(inputStream);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", certificate);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

        return sslContext;
    }

}
